#include "StdAfx.h"
#include "BlockChessboard.h"

namespace dhis
{
	CBlockChessboard::CBlockChessboard(const int& w, const int& h, const int& div)
	{
		m_width = w;
		m_height = h;

		int colRemainder = m_width%div;
		int rowRemainder = m_height%div;

		m_blockRow = m_height/div;
		m_blockCol = m_width/div;
		m_blockWidth = div;
		m_blockHeight = div;

		if (m_blockRow == 0) {
			m_blockRow = 1;
			m_blockHeight = m_width;
		} else {
			m_blockHeight = div + rowRemainder/m_blockRow;
		}

		if (m_blockCol == 0) {
			m_blockCol = 1;
			m_blockWidth = m_width;
		} else {
			m_blockWidth = div + colRemainder/m_blockCol;
		}


		for (int i = 0; i < m_blockRow; ++i) // row
		{
			for (int j = 0; j < m_blockCol; ++j) // col
			{
				int key = i*m_blockCol + j;
				CRectI rect;
				rect.X = j*m_blockWidth;
				rect.Y = i*m_blockHeight;
				if (i == (m_blockRow-1)) {
					rect.Height = m_height - rect.Y;
				} else {
					rect.Height = m_blockHeight;
				}

				if (j == (m_blockCol-1)) {
					rect.Width = m_width - rect.X;
				} else {
					rect.Width = m_blockWidth;
				}
				m_keys.push_back(key);
				m_rects.insert(std::make_pair(key,rect));
			}
		}
	}

	CBlockChessboard::~CBlockChessboard(void)
	{
		m_rects.clear();
	}

	int   CBlockChessboard::AtBlock(const int& row, const int& col) const
	{
		int block_row = row/m_blockHeight;
		if (block_row == m_blockRow) { block_row = m_blockRow-1; }
		int block_col = col/m_blockWidth;
		if (block_col == m_blockCol) { block_col = m_blockCol-1; }
		int key = block_row*m_blockCol + block_col;
		return key;
	}

	bool CBlockChessboard::IsBlockKey(const int& key) const
	{
		IntVec::const_iterator pos = std::find(m_keys.begin(),m_keys.end(),key);
		return pos != m_keys.end();
	}

	int  CBlockChessboard::AtBlock(const int& id) const
	{
		int row = CALC_ROW(id,m_width);
		int col = CALC_COL(id,Width());
		return AtBlock(row,col);
	}

}
